<template>
  <view class="reservation-page">
    <!-- 导航栏 -->
    <u-navbar 
      title="预约详情" 
      :border="true"
      left-icon="arrow-left"
      @leftClick="goBack"
    >
      <template #right>
        <u-icon name="more-dot-fill" size="20" @tap="showActions = true"></u-icon>
      </template>
    </u-navbar>
    
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <u-loading-icon mode="circle"></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 预约详情内容 -->
    <view v-else-if="reservation" class="reservation-content">
      <!-- 预约状态 -->
      <view class="status-section">
        <view class="status-card" :class="[getStatusClass(reservation.status)]">
          <view class="status-icon">
            <u-icon :name="getStatusIcon(reservation.status)" size="32" color="white"></u-icon>
          </view>
          <view class="status-info">
            <text class="status-text">{{ getStatusText(reservation.status) }}</text>
            <text class="status-desc">{{ getStatusDescription(reservation.status) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 预约码 -->
      <view class="code-section">
        <view class="section-title">预约码</view>
        <view class="code-card">
          <view class="code-display">
            <text class="code-text">{{ reservation.reservationCode }}</text>
            <u-icon name="copy" size="20" color="#409eff" @tap="copyCode"></u-icon>
          </view>
          <view v-if="reservation.qrCodeUrl" class="qr-code">
            <image :src="reservation.qrCodeUrl" mode="aspectFit" class="qr-image" />
            <text class="qr-hint">出示此二维码给店员扫描</text>
          </view>
        </view>
      </view>
      
      <!-- 文件信息 -->
      <view class="file-section">
        <view class="section-title">文件信息</view>
        <view class="file-card">
          <view class="file-header">
            <u-icon :name="getFileIcon(reservation.file.file_type)" size="24" color="#409eff"></u-icon>
            <view class="file-details">
              <text class="file-name">{{ reservation.file.original_name }}</text>
              <text class="file-meta">{{ formatFileSize(reservation.file.file_size) }} · {{ reservation.file.page_count || 1 }}页</text>
            </view>
            <u-icon name="arrow-right" size="16" color="#c0c4cc" @tap="viewFile"></u-icon>
          </view>
          <view v-if="reservation.file.preview_url" class="file-preview">
            <image :src="reservation.file.preview_url" mode="aspectFit" class="preview-image" @tap="previewFile" />
          </view>
        </view>
      </view>
      
      <!-- 打印参数 -->
      <view class="options-section">
        <view class="section-title">打印参数</view>
        <view class="options-card">
          <view class="option-item">
            <text class="option-label">纸张大小</text>
            <text class="option-value">{{ getPrintOptionText('paperSize', reservation.printOptions.paperSize) }}</text>
          </view>
          <view class="option-item">
            <text class="option-label">颜色类型</text>
            <text class="option-value">{{ getPrintOptionText('colorType', reservation.printOptions.colorType) }}</text>
          </view>
          <view class="option-item">
            <text class="option-label">打印质量</text>
            <text class="option-value">{{ getPrintOptionText('printQuality', reservation.printOptions.printQuality) }}</text>
          </view>
          <view v-if="reservation.printOptions.bindingType" class="option-item">
            <text class="option-label">装订方式</text>
            <text class="option-value">{{ getPrintOptionText('bindingType', reservation.printOptions.bindingType) }}</text>
          </view>
          <view class="option-item">
            <text class="option-label">打印份数</text>
            <text class="option-value">{{ reservation.quantity }}份</text>
          </view>
          <view v-if="reservation.printOptions.duplex" class="option-item">
            <text class="option-label">双面打印</text>
            <text class="option-value">是</text>
          </view>
          <view v-if="reservation.printOptions.pageRange" class="option-item">
            <text class="option-label">页面范围</text>
            <text class="option-value">{{ reservation.printOptions.pageRange }}</text>
          </view>
        </view>
      </view>
      
      <!-- 费用信息 -->
      <view class="cost-section">
        <view class="section-title">费用信息</view>
        <view class="cost-card">
          <view class="cost-item">
            <text class="cost-label">总页数</text>
            <text class="cost-value">{{ reservation.totalPages }}页</text>
          </view>
          <view class="cost-item">
            <text class="cost-label">打印份数</text>
            <text class="cost-value">{{ reservation.quantity }}份</text>
          </view>
          <view class="cost-item total">
            <text class="cost-label">消费积分</text>
            <text class="cost-value highlight">{{ reservation.pointsCost }}积分</text>
          </view>
        </view>
      </view>
      
      <!-- 时间信息 -->
      <view class="time-section">
        <view class="section-title">时间信息</view>
        <view class="time-card">
          <view class="time-item">
            <text class="time-label">预约时间</text>
            <text class="time-value">{{ formatDateTime(reservation.reservedAt) }}</text>
          </view>
          <view class="time-item">
            <text class="time-label">过期时间</text>
            <text class="time-value" :class="{ expired: isExpired }">{{ formatDateTime(reservation.expiresAt) }}</text>
          </view>
          <view v-if="reservation.confirmedAt" class="time-item">
            <text class="time-label">确认时间</text>
            <text class="time-value">{{ formatDateTime(reservation.confirmedAt) }}</text>
          </view>
          <view v-if="reservation.completedAt" class="time-item">
            <text class="time-label">完成时间</text>
            <text class="time-value">{{ formatDateTime(reservation.completedAt) }}</text>
          </view>
        </view>
      </view>
      
      <!-- 店铺信息 -->
      <view v-if="reservation.storeLocation" class="store-section">
        <view class="section-title">店铺信息</view>
        <view class="store-card">
          <u-icon name="map-pin" size="20" color="#409eff"></u-icon>
          <text class="store-location">{{ reservation.storeLocation }}</text>
        </view>
      </view>
      
      <!-- 备注信息 -->
      <view v-if="reservation.notes" class="notes-section">
        <view class="section-title">备注信息</view>
        <view class="notes-card">
          <text class="notes-text">{{ reservation.notes }}</text>
        </view>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <u-button 
          v-if="canCancel"
          type="error" 
          @click="showCancelModal = true"
          class="action-btn"
        >
          取消预约
        </u-button>
        
        <u-button 
          v-if="canRefresh"
          type="info" 
          @click="refreshReservation"
          class="action-btn"
        >
          刷新状态
        </u-button>
        
        <u-button 
          type="primary" 
          @click="shareReservation"
          class="action-btn"
        >
          分享预约码
        </u-button>
      </view>
      
      <!-- 使用说明 -->
      <view class="instructions-section">
        <view class="section-title">使用说明</view>
        <view class="instructions-card">
          <view class="instruction-item">
            <text class="instruction-number">1</text>
            <text class="instruction-text">携带预约码到任意合作打印店</text>
          </view>
          <view class="instruction-item">
            <text class="instruction-number">2</text>
            <text class="instruction-text">出示二维码或告知预约码给店员</text>
          </view>
          <view class="instruction-item">
            <text class="instruction-number">3</text>
            <text class="instruction-text">店员确认后开始打印，完成后取走文件</text>
          </view>
          <view class="instruction-item">
            <text class="instruction-number">4</text>
            <text class="instruction-text">预约有效期24小时，过期自动取消并退还积分</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 错误状态 -->
    <view v-else class="error-container">
      <u-empty 
        mode="error" 
        text="预约不存在或已被删除"
        textColor="#f56c6c"
      >
        <template #bottom>
          <u-button 
            type="primary" 
            size="small"
            @click="goBack"
          >
            返回
          </u-button>
        </template>
      </u-empty>
    </view>
    
    <!-- 操作菜单 -->
    <u-action-sheet 
      :show="showActions" 
      :actions="actionList"
      @close="showActions = false"
      @select="handleAction"
      title="预约操作"
    />
    
    <!-- 取消确认弹窗 -->
    <u-modal 
      :show="showCancelModal"
      title="取消预约"
      content="确定要取消这个预约吗？取消后积分将退还到您的账户。"
      @confirm="cancelReservation"
      @cancel="showCancelModal = false"
    />
  </view>
</template>

<script>
export default {
  name: 'PrintReservation',
  data() {
    return {
      reservationId: null,
      reservation: null,
      loading: false,
      showActions: false,
      showCancelModal: false,
      printConfigs: {},
      actionList: [
        { name: '刷新状态', value: 'refresh' },
        { name: '查看文件', value: 'viewFile' },
        { name: '分享预约码', value: 'share' },
        { name: '取消预约', value: 'cancel', color: '#f56c6c' }
      ]
    }
  },
  
  computed: {
    // 是否已过期
    isExpired() {
      return this.reservation && new Date() > new Date(this.reservation.expiresAt)
    },
    
    // 是否可以取消
    canCancel() {
      return this.reservation && ['pending', 'confirmed'].includes(this.reservation.status)
    },
    
    // 是否可以刷新
    canRefresh() {
      return this.reservation && !['completed', 'cancelled'].includes(this.reservation.status)
    }
  },
  
  onLoad(options) {
    this.reservationId = parseInt(options.id)
    if (this.reservationId) {
      this.loadReservationDetail()
      this.loadPrintConfigs()
    }
  },
  
  onShow() {
    // 页面显示时刷新状态
    if (this.reservationId && this.canRefresh) {
      this.refreshReservation()
    }
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 加载预约详情
    async loadReservationDetail() {
      this.loading = true
      
      try {
        const response = await this.$http.get(`/api/print/reservations/${this.reservationId}`)
        
        if (response.data.success) {
          this.reservation = response.data.data
        } else {
          throw new Error(response.data.message)
        }
      } catch (error) {
        console.error('加载预约详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 加载打印配置
    async loadPrintConfigs() {
      try {
        const response = await this.$http.get('/api/print/configs')
        if (response.data.success) {
          this.printConfigs = response.data.data
        }
      } catch (error) {
        console.error('加载打印配置失败:', error)
      }
    },
    
    // 刷新预约状态
    async refreshReservation() {
      try {
        await this.loadReservationDetail()
        uni.showToast({
          title: '状态已刷新',
          icon: 'success'
        })
      } catch (error) {
        console.error('刷新状态失败:', error)
      }
    },
    
    // 取消预约
    async cancelReservation() {
      this.showCancelModal = false
      
      try {
        uni.showLoading({ title: '取消中...' })
        
        const response = await this.$http.post(`/api/print/reservations/${this.reservationId}/cancel`)
        
        if (response.data.success) {
          uni.showToast({
            title: '预约已取消',
            icon: 'success'
          })
          
          // 刷新预约详情
          this.loadReservationDetail()
        }
      } catch (error) {
        console.error('取消预约失败:', error)
        uni.showToast({
          title: (error.response && error.response.data && error.response.data.message) || '取消失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 复制预约码
    copyCode() {
      uni.setClipboardData({
        data: this.reservation.reservationCode,
        success: () => {
          uni.showToast({
            title: '预约码已复制',
            icon: 'success'
          })
        }
      })
    },
    
    // 查看文件
    viewFile() {
      if (this.reservation && this.reservation.file) {
        uni.navigateTo({
          url: `/pages/files/detail?id=${this.reservation.file.id}`
        })
      }
    },
    
    // 预览文件
    previewFile() {
      if (this.reservation && this.reservation.file && this.reservation.file.preview_url) {
        uni.previewImage({
          urls: [this.reservation.file.preview_url],
          current: this.reservation.file.preview_url
        })
      }
    },
    
    // 分享预约码
    shareReservation() {
      const shareContent = `我的打印预约码：${this.reservation.reservationCode}\n文件：${this.reservation.file.original_name}\n请在${this.formatDateTime(this.reservation.expiresAt)}前完成打印`
      
      uni.share({
        provider: 'weixin',
        scene: 'WXSceneSession',
        type: 1,
        summary: shareContent,
        success: () => {
          uni.showToast({
            title: '分享成功',
            icon: 'success'
          })
        }
      })
    },
    
    // 处理操作菜单
    handleAction(action) {
      this.showActions = false
      
      switch (action.value) {
        case 'refresh':
          this.refreshReservation()
          break
        case 'viewFile':
          this.viewFile()
          break
        case 'share':
          this.shareReservation()
          break
        case 'cancel':
          if (this.canCancel) {
            this.showCancelModal = true
          }
          break
      }
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        'pending': 'status-pending',
        'confirmed': 'status-confirmed',
        'processing': 'status-processing',
        'completed': 'status-completed',
        'cancelled': 'status-cancelled',
        'expired': 'status-expired'
      }
      return classMap[status] || 'status-pending'
    },
    
    // 获取状态图标
    getStatusIcon(status) {
      const iconMap = {
        'pending': 'clock',
        'confirmed': 'checkmark-circle',
        'processing': 'reload',
        'completed': 'checkmark-done-circle',
        'cancelled': 'close-circle',
        'expired': 'time'
      }
      return iconMap[status] || 'clock'
    },
    
    // 获取状态文本
    getStatusText(status) {
      const textMap = {
        'pending': '等待确认',
        'confirmed': '已确认',
        'processing': '打印中',
        'completed': '已完成',
        'cancelled': '已取消',
        'expired': '已过期'
      }
      return textMap[status] || status
    },
    
    // 获取状态描述
    getStatusDescription(status) {
      const descMap = {
        'pending': '请携带预约码到店确认',
        'confirmed': '店员已确认，准备打印',
        'processing': '正在打印中，请稍候',
        'completed': '打印已完成，请取走文件',
        'cancelled': '预约已取消，积分已退还',
        'expired': '预约已过期，积分已退还'
      }
      return descMap[status] || ''
    },
    
    // 获取打印选项文本
    getPrintOptionText(category, value) {
      const categoryMap = {
        'paperSize': 'paper_size',
        'colorType': 'color_type',
        'printQuality': 'print_quality',
        'bindingType': 'binding_type'
      }
      
      const configCategory = categoryMap[category]
      if (!configCategory || !this.printConfigs[configCategory]) {
        return value
      }
      
      const option = this.printConfigs[configCategory].find(opt => opt.value === value)
      return option ? option.displayName : value
    },
    
    // 获取文件图标
    getFileIcon(fileType) {
      if (!fileType) return 'file-text'
      
      if (fileType.includes('pdf')) return 'file-pdf'
      if (fileType.includes('word') || fileType.includes('document')) return 'file-word'
      if (fileType.includes('excel') || fileType.includes('sheet')) return 'file-excel'
      if (fileType.includes('powerpoint') || fileType.includes('presentation')) return 'file-ppt'
      if (fileType.includes('image')) return 'image'
      if (fileType.includes('text')) return 'file-text'
      
      return 'file'
    },
    
    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },
    
    // 格式化日期时间
    formatDateTime(dateString) {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.reservation-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.loading-container, .error-container {
  padding: 120rpx 40rpx;
  text-align: center;
  
  .loading-text {
    display: block;
    margin-top: 20rpx;
    font-size: 28rpx;
    color: #909399;
  }
}

.reservation-content {
  padding-bottom: 40rpx;
}

.status-section, .code-section, .file-section, .options-section, 
.cost-section, .time-section, .store-section, .notes-section, .instructions-section {
  background: white;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #303133;
  margin-bottom: 30rpx;
}

.status-card {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-radius: 16rpx;
  
  &.status-pending {
    background: linear-gradient(135deg, #ffa726, #ff9800);
  }
  
  &.status-confirmed {
    background: linear-gradient(135deg, #42a5f5, #2196f3);
  }
  
  &.status-processing {
    background: linear-gradient(135deg, #ab47bc, #9c27b0);
  }
  
  &.status-completed {
    background: linear-gradient(135deg, #66bb6a, #4caf50);
  }
  
  &.status-cancelled, &.status-expired {
    background: linear-gradient(135deg, #ef5350, #f44336);
  }
  
  .status-icon {
    margin-right: 20rpx;
  }
  
  .status-info {
    flex: 1;
    
    .status-text {
      display: block;
      font-size: 36rpx;
      color: white;
      font-weight: 600;
      margin-bottom: 8rpx;
    }
    
    .status-desc {
      font-size: 28rpx;
      color: rgba(255, 255, 255, 0.9);
    }
  }
}

.code-card {
  text-align: center;
  
  .code-display {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 30rpx;
    
    .code-text {
      font-size: 40rpx;
      font-weight: 600;
      color: #303133;
      font-family: 'Courier New', monospace;
      margin-right: 20rpx;
    }
  }
  
  .qr-code {
    .qr-image {
      width: 300rpx;
      height: 300rpx;
      margin-bottom: 20rpx;
    }
    
    .qr-hint {
      font-size: 26rpx;
      color: #909399;
    }
  }
}

.file-card {
  .file-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
    
    .file-details {
      margin-left: 16rpx;
      flex: 1;
      
      .file-name {
        display: block;
        font-size: 30rpx;
        color: #303133;
        font-weight: 500;
        margin-bottom: 8rpx;
      }
      
      .file-meta {
        font-size: 26rpx;
        color: #909399;
      }
    }
  }
  
  .file-preview {
    .preview-image {
      width: 100%;
      height: 200rpx;
      border-radius: 12rpx;
    }
  }
}

.options-card, .cost-card, .time-card {
  .option-item, .cost-item, .time-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.total {
      padding-top: 30rpx;
      border-top: 2rpx solid #f0f0f0;
      margin-top: 20rpx;
    }
    
    .option-label, .cost-label, .time-label {
      font-size: 30rpx;
      color: #606266;
    }
    
    .option-value, .cost-value, .time-value {
      font-size: 30rpx;
      color: #303133;
      font-weight: 500;
      
      &.highlight {
        color: #409eff;
        font-size: 34rpx;
        font-weight: 600;
      }
      
      &.expired {
        color: #f56c6c;
      }
    }
  }
}

.store-card {
  display: flex;
  align-items: center;
  
  .store-location {
    margin-left: 16rpx;
    font-size: 30rpx;
    color: #303133;
  }
}

.notes-card {
  .notes-text {
    font-size: 30rpx;
    color: #606266;
    line-height: 1.6;
  }
}

.instructions-card {
  .instruction-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 24rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .instruction-number {
      width: 40rpx;
      height: 40rpx;
      background: #409eff;
      color: white;
      border-radius: 50%;
      text-align: center;
      line-height: 40rpx;
      font-size: 24rpx;
      font-weight: 600;
      margin-right: 20rpx;
      flex-shrink: 0;
    }
    
    .instruction-text {
      flex: 1;
      font-size: 28rpx;
      color: #606266;
      line-height: 1.5;
      padding-top: 8rpx;
    }
  }
}

.action-buttons {
  padding: 40rpx 20rpx;
  
  .action-btn {
    width: 100%;
    height: 88rpx;
    border-radius: 44rpx;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>